package com.yz.dba.thread;

import com.yz.dba.service.TaskCountService;
import com.yz.common.utils.JdbcUtils;
import com.yz.dba.utils.SpringContextUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author 段成
 * @date 2019/12/2 - 13:31
 */
public class ThreadUtil implements Runnable{

    //String taskId = "task20191203";
    TaskCountService taskCountService = SpringContextUtil.getBean("taskCountService");

    StringRedisTemplate redisTemplate = SpringContextUtil.getBean("stringRedisTemplate");


    private Map dataSourceMap;

    private Map targetMap;


    private String sourceTableName;
    private String targetTableName;


    private String querySql;
    private String taskNumber;
    private String fieldNames;


    public ThreadUtil(Map dataSourceMap, Map targetMap, String sourceTableName, String targetTableName, String querySql, String taskNumber, String fieldNames) {
        this.dataSourceMap = dataSourceMap;
        this.targetMap = targetMap;
        this.sourceTableName = sourceTableName;
        this.targetTableName = targetTableName;
        this.querySql = querySql;
        this.taskNumber = taskNumber;
        this.fieldNames = fieldNames;
    }

    public ThreadUtil() {
    }

    //synchronized
    @Override
    public synchronized void run() {

        taskCountService.updateThreadCount(taskNumber,1);
        //每次开启一个子线程 redis中的监控数+1
        this.updateThreadCount(taskNumber,1);

        try {
            List<Map> dataSourceList = JdbcUtils.queryData(dataSourceMap, querySql);
            List<String> sqlList = JdbcUtils.checkSql(dataSourceList, targetTableName,fieldNames);

            JdbcUtils.affair2(targetMap,sqlList);


            //监控线程数 每次开启一个子线程 redis中的监控数-1

            int updateThreadCount = this.updateThreadCount(taskNumber, -1);
            if(updateThreadCount<0){
                //初始化task_count redis
                redisTemplate.opsForValue().set("ThreadCount_"+taskNumber,"0");
            }
            taskCountService.updateThreadCount(taskNumber,-1);

        } catch (SQLException e) {
            e.printStackTrace();
        }



    }

    private int updateThreadCount(String taskNumber, int variable) {
        int threadCount = Integer.parseInt(redisTemplate.opsForValue().get("ThreadCount_"+taskNumber));
        redisTemplate.opsForValue().set("ThreadCount_"+taskNumber,threadCount+variable+"");
        return threadCount+variable;
    }



}
